﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CSP.Bll.CommonBll;
using CSP.Bll.IObjectBlls;
using CSP.Dao.IObjectDaos.CSP;
using CSP.Common.Factories;
using CSP.Dao;
using CSP.Model.CSP;
using System.Collections.ObjectModel;

namespace CSP.Bll.ObjectBlls
{
    public class AddressBll : CSPCommonBll, IAddressBll
    {
        /// <summary>
        /// 缓存键值
        /// </summary>
        private const string CACHEKEY = "Address_";

        private IAddressDao _addressDao;

        public AddressBll()
        {
            _cacheProvider = CachedProviderFactory.GetMemCachedProvider();
            _addressDao = CSPDaoFactory.GetInstance().GetAddressDao();
        }

        public Address GetDataById(int id)
        {
            return _addressDao.GetDataById(id);
        }

        public ICollection<Address> GeDatatByIds(int[] Ids)
        {
            throw new NotImplementedException();
        }

        public void Add(Address obj)
        {
            _addressDao.Add(obj);
        }

        public void Update(Address obj)
        {
            _addressDao.Update(obj);
        }

        public void DeleteById(int id)
        {
            _addressDao.DeleteById(id);
        }

        public Address DeleteByIdAndUser(int id, string userName)
        {
            Address address=_addressDao.GetByIdAndUser(id, userName);
            //如果不存在关系那么物理删除
            if (address.ServiceInfoAddressRels.Count()==0)
            {
                _addressDao.DeleteByIdAndUser(id, userName);
            }
            else //否则逻辑删除
            {
                address.Status=1;
                _addressDao.Update(address);
            }
            return address;
        }

        public void RefreshCache()
        {
            throw new NotImplementedException();
        }

        public ICollection<Address> FindByUser(string userName)
        {
            string cacheKey = CACHEKEY + userName.ToString();
            ICollection<Address> addresses = _cacheProvider.GetData<Collection<Address>>(cacheKey);
            if (addresses == null)
            {
                addresses = _addressDao.FindByUser(userName);
                _cacheProvider.AddData(cacheKey, addresses, DateTime.Now.AddHours(1));
            }

            return addresses;
        }

        public Address GetByIdAndUser(int id, string userName)
        {
            return _addressDao.GetByIdAndUser(id, userName);
        }

    }
}
